public class Main {
    public static void main(String[] args) {
        MySingleList mySingleList1 = new MySingleList();
        mySingleList1.addLast(12);
        mySingleList1.addLast(23);
        mySingleList1.addLast(34);
        mySingleList1.addLast(45);
        mySingleList1.addLast(56);
        mySingleList1.display();

        MySingleList mySingleList2 = new MySingleList();
        mySingleList2.addLast(8);
        mySingleList2.addLast(15);
        mySingleList2.addLast(30);
        mySingleList2.addLast(40);
        mySingleList2.addLast(78);
        mySingleList2.display();

        createIntersect(mySingleList1.head, mySingleList2.head);
        MySingleList.ListNode nh = getIntersectionNode(mySingleList1.head, mySingleList2.head);
        System.out.println(nh.val);
    }
    public static MySingleList.ListNode getIntersectionNode(MySingleList.ListNode headA,MySingleList.ListNode headB){
        int lenA = 0;
        int lenB = 0;

        MySingleList.ListNode PL = headA;
        MySingleList.ListNode PS = headB;

        while (PL != null);{
            lenA++;
            PL = PL.next;
        }
        while (PS != null);{
            lenB++;
            PS = PS.next;
        }
        int len = lenA - lenB;
        if (len < 0){
            PL = headB;
            PS = headA;
            len = lenB - lenA;
        }
        for (int i = 0; i < len; i++) {
            PL = PL.next;
        }
        while (PL != PS){
            PL = PL.next;
            PS = PS.next;
        }
        return PL;
    }
    public static void createIntersect(MySingleList.ListNode headA,
                                       MySingleList.ListNode headB){
        headB.next.next = headA.next.next;
    }
}